#include "bsp_ft5x06.h"

#define TAG "ft6336"
#ifndef CONFIG_LCD_HRES
#define CONFIG_LCD_HRES BSP_LCD_H_RES
#endif

#ifndef CONFIG_LCD_VRES
#define CONFIG_LCD_VRES BSP_LCD_V_RES
#endif

esp_lcd_touch_handle_t tp;

void bsp_ft5x06_init()
{
    esp_lcd_panel_io_i2c_config_t io_config = {
        .dev_addr = 0x38,
        .control_phase_bytes = 1,
        .dc_bit_offset = 0,
        .lcd_cmd_bits = 8,
        .flags =
            {
                .disable_control_phase = 1,
            },
#if !CONFIG_USE_OLD_I2C_DRIVER
        .scl_speed_hz = MASTER_FREQUENCY,
#endif
    };

    esp_lcd_touch_config_t tp_cfg = {
        .x_max = CONFIG_LCD_HRES,
        .y_max = CONFIG_LCD_VRES,
        .rst_gpio_num = -1,
        .int_gpio_num = -1,
        .levels = {
            .reset = 0,
            .interrupt = 0,
        },
        .flags = {
            .swap_xy = 0,
            .mirror_x = 0,
            .mirror_y = 0,
        },
    };

    esp_lcd_panel_io_handle_t ft5x06_handle;

    esp_lcd_new_panel_io_i2c(I2C_BUS, &io_config, &ft5x06_handle);
    esp_lcd_touch_new_i2c_ft5x06(ft5x06_handle, &tp_cfg, &tp);

    ESP_LOGI(TAG, "ft5x06_init.");
}

bool bsp_ft5x06_get_point(uint16_t *x, uint16_t *y)
{
    bool press = false;
    uint16_t touchpad_x[1] = {0};
    uint16_t touchpad_y[1] = {0};
    uint8_t touchpad_cnt = 0;
    esp_lcd_touch_read_data(tp);
    bool touchpad_pressed = esp_lcd_touch_get_coordinates(tp, touchpad_x, touchpad_y, NULL, &touchpad_cnt, 5);

    if (touchpad_pressed && touchpad_cnt > 0)
    {
        *x = touchpad_x[0];
        *y = touchpad_y[0];
        ESP_LOGI(TAG, "touch X: %d ,Y: %d", *x, *y);
        press = true;
    }
    return press;
}